package com.ly.hotel.spainterface.jg.adapter;

import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.MassageItemBean;
import com.ly.hotel.spainterface.jg.bean.OnAddToBasketCompleted;
import com.ly.hotel.spainterface.jg.utils.AvoidDoubleClickedUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;
import com.ly.hotel.spainterface.jg.view.CustomBuyGoodsDialogFragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by ThinkPad on 2018/2/2.
 */

public class MassageItemAdapter extends RecyclerView.Adapter<MassageItemAdapter.ViewHolder> implements OnAddToBasketCompleted{

    private List<MassageItem> massageItemList;
    private RecyclerView massageItemRecyclerView;
    private Context context;
    private final LruCache<String, Bitmap> mMemoryCache;
    private int mFirstVisableItem;// RecyclerView当中可见的第一个View的序号
    private int mLastVisableItem;// RecyclerView当中可见的最后一个View的序号
    private int mVisableItemCount;// RecyclerView当中可见View的数量
    private boolean isFirstEnter = true;
    private final Set<GetBitmapTask> tasksCollection;
    private String serverIP;
    private String serverPORT;
    private String cashierIP;
    private String cashierPORT;
    private String tvName;
    private String categoryName;
    private FragmentManager fragmentManager;
    private int limitedGoodsNum;// 限制购买的商品数量
    private OnAddToBasketCompleted onAddToBasketCompleted;
    private List<MassageItem> massageItems;
    private boolean isOnlySee;

    public MassageItemAdapter(List<MassageItem> massageItemList, RecyclerView massageItemRecyclerView,
                              String serverIP, String serverPORT, FragmentManager fragmentManager,int limitedGoodsNum,
                              String cashierIP,String cashierPORT,String tvName,String categoryName,
                              List<MassageItem> massageItems,boolean isOnlySee){

        this.massageItemList = massageItemList;
        this.massageItemRecyclerView = massageItemRecyclerView;
        tasksCollection = new HashSet<>();
        this.serverIP = serverIP;
        this.serverPORT = serverPORT;
        this.cashierIP = cashierIP;
        this.cashierPORT = cashierPORT;
        this.tvName = tvName;
        this.categoryName = categoryName;
        this.fragmentManager = fragmentManager;
        this.limitedGoodsNum = limitedGoodsNum;
        this.massageItems = massageItems;
        this.isOnlySee = isOnlySee;

        int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取应用可用的最大内存
        int cacheSize = maxMemory / 8;// 以应用的1/8作为缓存
        // 以图片的链接作为键，Bitmap对象作为值
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
        setRecyclerViewOnScroll();
    }

    public void setOnAddToBasketCompleted(OnAddToBasketCompleted onAddToBasketCompleted) {
        this.onAddToBasketCompleted = onAddToBasketCompleted;
    }

    // 接口回调
    @Override
    public void addToBasketCompleted(MassageItem massageItem, int num) {
        Log.d("CustomBuyGoods",massageItem.getName());
        Log.d("CustomBuyGoods",num + "");
        onAddToBasketCompleted.addToBasketCompleted(massageItem,num);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        CardView cardView;
        ImageView massageItemImage;
        TextView massageItemName;
        TextView massageItemPrice;

        public ViewHolder(View view){
            super(view);
            cardView = (CardView) view;
            massageItemImage = (ImageView) view.findViewById(R.id.massageitem_image);
            massageItemName = (TextView) view.findViewById(R.id.massageitem_name);
            massageItemPrice = (TextView) view.findViewById(R.id.massageitem_price);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        if(context == null){
            context = parent.getContext();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.jg_recyclerview_massageitem_item,parent,false);
        final ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final MassageItem massageItem = massageItemList.get(position);
        final String massageItemId = massageItem.getId();
        if(massageItems != null && massageItems.size() > 0){
            for(int i = 0;i < massageItems.size();i ++){
                if(massageItems.get(i).getId().equals(massageItemId)){
                    massageItem.setNum(massageItems.get(i).getNum());
                }
            }
        }else{
            Log.d("JgMainActivity","重置为1");
            massageItem.setNum(1);
        }
        final String massageItemName = massageItem.getName();
        final double massageItemPrice = massageItem.getPrice();
        final String massageItemUnit = massageItem.getUnit();
        final String imageUrl = "http://" + serverIP + ":" + serverPORT + "/upload/interface/consume/pic/" + massageItemId + ".jpg";

        ImageView massageItemImage = holder.massageItemImage;
        massageItemImage.setTag(imageUrl);// 设置tag，保证加载的时候不会混乱
        holder.massageItemName.setText(massageItemName);
        holder.massageItemPrice.setText(String.valueOf(massageItemPrice) + "元/" + massageItemUnit);
        setImageView(imageUrl,massageItemImage);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒，则不执行下面的代码
                    return;
                }
                CustomBuyGoodsDialogFragment buyGoodsDialogFragment = new CustomBuyGoodsDialogFragment();
                buyGoodsDialogFragment.setCancelable(false);
                buyGoodsDialogFragment.setOnAddToBasketCompleted(MassageItemAdapter.this);
                Bundle bundle = new Bundle();
                MassageItemBean massageItemBean = new MassageItemBean();
                massageItemBean.setMassageItem(massageItem);
                bundle.putString("cashierIP",cashierIP);
                bundle.putString("cashierPORT",cashierPORT);
                bundle.putString("tvName",tvName);
                bundle.putString("categoryName",categoryName);
                bundle.putSerializable("massageItemBean",massageItemBean);
                bundle.putString("imageUrl",imageUrl);
                bundle.putInt("limitedGoodsNum",limitedGoodsNum);
                bundle.putBoolean("isOnlySee",isOnlySee);
                buyGoodsDialogFragment.setArguments(bundle);
                buyGoodsDialogFragment.show(fragmentManager,"CustomBuyGoodsDialogFragment");
            }
        });
    }

    @Override
    public int getItemCount() {// 返回要显示的项目数量
        return massageItemList.size();
    }

    // 设置图片
    public void setImageView(String url,ImageView imageView){
        Bitmap bitmap = getBitmapFromMemoryCache(url);
        if(bitmap != null){
            imageView.setImageBitmap(bitmap);
        }else{
            imageView.setImageResource(R.mipmap.jg_massage_item_default);// 设置默认图片
        }
    }

    // 设置Recyclerview的滑动事件
    private void setRecyclerViewOnScroll(){
        massageItemRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            // 状态改变的时候调用
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE){// 停止滚动时，加载图片
                    loadBitmaps(mFirstVisableItem,mVisableItemCount);
                }else{
                    cancelAllTask();// 滚动的时候，取消所有
                }
            }

            // 滚动的时候调用
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                mFirstVisableItem = layoutManager.findFirstVisibleItemPosition();
                mLastVisableItem = layoutManager.findLastVisibleItemPosition();
                mVisableItemCount = mLastVisableItem - mFirstVisableItem + 1;
                if(isFirstEnter && mLastVisableItem > 0){// 第一次进入，需要从网络中加载图片
                    loadBitmaps(mFirstVisableItem,mVisableItemCount);
                    isFirstEnter = false;
                }
                //Log.d("JgActivity","mFirstVisableItem=" + mFirstVisableItem + ",mLastVisableItem=" + mLastVisableItem + ",mVisableItemCount=" + mVisableItemCount);
            }
        });
    }

    // 将Bitmap添加到LrcCache缓存当中
    public void addBitmapToMemoryCache(String key,Bitmap bitmap){
        if(getBitmapFromMemoryCache(key) == null){
            mMemoryCache.put(key,bitmap);
        }
    }

    // 从LruCache缓存中获得Bitmap对象
    public Bitmap getBitmapFromMemoryCache(String key){
        return mMemoryCache.get(key);
    }

    // 加载Bitmap
    public void loadBitmaps(int firstVisiableItem,int mVisableItemCount){
        try{
            for(int i = firstVisiableItem;i < firstVisiableItem + mVisableItemCount;i ++){
                String imageUrl = "http://" + serverIP + ":" + serverPORT + "/upload/interface/consume/pic/" + massageItemList.get(i).getId() + ".jpg";
                Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
                if(bitmap == null){// 缓存中没有
                    GetBitmapTask task = new GetBitmapTask();
                    tasksCollection.add(task);// 异步下载图片任务添加到集合当中
                    task.execute(imageUrl);// 开启下载任务
                }else{// 缓存中有
                    ImageView massageItemImage = (ImageView) massageItemRecyclerView.findViewWithTag(imageUrl);
                    if(massageItemImage != null && bitmap != null){
                        massageItemImage.setImageBitmap(bitmap);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 取消所有异步任务
    public void cancelAllTask(){
        if(tasksCollection != null){
            for (GetBitmapTask task : tasksCollection) {
                task.cancel(false);
            }
        }
    }

    class GetBitmapTask extends AsyncTask<String,Void,Bitmap>{

        private String imageUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadBitmap(imageUrl);
            if(bitmap != null){
                addBitmapToMemoryCache(imageUrl,bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            ImageView massageItemImage = (ImageView) massageItemRecyclerView.findViewWithTag(imageUrl);
            if(bitmap != null && massageItemImage != null){// 给ImageView设置图片
                massageItemImage.setImageBitmap(bitmap);
                tasksCollection.remove(this);// 移除当前任务
            }
        }

        // 从网络中下载图片；
        private Bitmap downloadBitmap(String imageUrl){
            InputStream is = OkHttpUtils.getInstance().getImageResource(imageUrl);
            Bitmap bitmap = null;
            if(is != null){
                bitmap = decodeSampleBitmapFromStream(is,400,200);
            }
            return bitmap;
        }
    }

    // 将字节流转换为Bitmap对象
    public static Bitmap decodeSampleBitmapFromStream(InputStream is, int reqWidth, int reqHeight){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 设置为true，系统不会分配内存
        byte[] data = inputStreamToByteArray(is);
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = caculateInSampleSize(options,reqWidth,reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        return bitmap;
    }

    //计算inSampleSize值,reqWidth为ImageView要求的宽度
    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeigh){
        // 获得资源图片的宽度和高度
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if(width > reqWidth || height >reqHeigh){
            // 计算出资源图片和目标图片之间的比例
            final int heightRadio = Math.round((float) height / (float) reqHeigh);
            final int widthRadio = Math.round((float) width / (float) reqWidth);
            // 选择比例最小的作为inSampleSzie值
            inSampleSize = heightRadio < widthRadio ? heightRadio : widthRadio;
        }
        return inSampleSize;
    }

    // 将字节流转化为字节数组
    public static byte[] inputStreamToByteArray(InputStream inputStream) {
        try{
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ( (len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return outputStream.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
